package cellphone

import (
	"bytes"
	"database/sql"
	"fmt"
	"strconv"
	"time"

	"shqsoft.cn/pas3ui/base"
)

type DataItem struct {
	Date  string  `json:"date"`  //String   | 日期
	Money float64 `json:"money"` //Number   | 排行日均
}

func GetBrokenData(userID int, tpStr string, date string) (dis []DataItem, err error) {
	var tp int
	tp, err = strconv.Atoi(tpStr)
	if tp < 0 || tp > 4 || err != nil {
		err = fmt.Errorf("无效的type:%s", tpStr)
		return
	}
	var buff bytes.Buffer
	buff.WriteString("select toString(DTID),sum(")
	buff.WriteString(COLNAMES[tp])
	buff.WriteString(") ACBL from DFKB_EMPL_INDEX where DTID>=toDate(?) and DTID<=toDate(?)")
	// if tp == 0 || tp == 1 {
	// 	buff.WriteString(" AND CYNO='01'")
	// }
	var rtype uint8
	rtype, err = GetUserRoleType(userID)
	if rtype == 2 {
		buff.WriteString(" and EMID=")
		buff.WriteString(strconv.Itoa(userID))
	} else if rtype == 1 {
		buff.WriteString(" and EMID in (with dictGetUInt32('DICT_USER_DEPT','PDID',toUInt64(")
		buff.WriteString(strconv.Itoa(userID))
		buff.WriteString(")) AS PDID2 select toUInt32(EMID) from DICT_USER_DEPT where PDID =PDID2)")
	}
	buff.WriteString(" group by DTID order by DTID")
	odsDate, err := time.Parse("2006-01-02", date)
	if err != nil {
		return
	}
	edateStr := odsDate.Format("2006-01-02")
	sdateStr := odsDate.AddDate(0, 0, -30).Format("2006-01-02")
	var rows *sql.Rows
	rows, err = base.CHDB.Raw(buff.String(), sdateStr, edateStr).Rows()
	if err != nil {
		return
	}
	defer rows.Close()
	dis = make([]DataItem, 0, 30)
	for rows.Next() {
		var di DataItem
		rows.Scan(&di.Date, &di.Money)
		dis = append(dis, di)
	}
	return
}
